package com.sgb.kjwl.view.ui.activity.material.hall;

import android.content.Intent;
import android.text.TextUtils;

import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.model.entity.BiddingEntity;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.pick.TenderAllListNewEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.repository.PickRepertory;
import com.sgb.kjwl.view.ui.activity.pick.PickInquireByLetterActivity;
import com.sgb.kjwl.view.ui.activity.pick.ReportActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.base.model.entity.H5ReEntity;
import com.swgk.core.base.model.entity.ListResponse;
import com.swgk.core.dialog.DialogHelper;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.areapopup.AddressEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NewPickBiddingModel extends BaseViewModel {

    private NewPickBiddingListFragment newPickBiddingListFragment;
    private PickRepertory repertory;
    private HashMap map;
    private int page = 1;
    private PickSelectEntity mAll;

    public NewPickBiddingModel(NewPickBiddingListFragment newPickBiddingListFragment, PickRepertory repertory) {
        this.newPickBiddingListFragment = newPickBiddingListFragment;
        this.repertory = repertory;

        mAll = new PickSelectEntity();
        mAll.setNo("");
        mAll.setProjectscale("全部");
    }


    public void getSelecteScaleData() {
        APIManager.getInstance().getPickAPI().getProjectScale("0").enqueue(new ICallBack<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PickSelectEntity>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
//                    activity.setScaleDatas(data.getData());
                }
            }
        });
    }

    public void getPickTimes() {
        APIManager.getInstance().getPickAPI().getPickTimes().enqueue(new ICallBack<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PickSelectEntity>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    newPickBiddingListFragment.setTimeDatas(data.getData());
                }
            }
        });
    }

    public void getPriceData() {
        APIManager.getInstance().getPickAPI().getProjectMoney().enqueue(new ICallBack<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PickSelectEntity>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    newPickBiddingListFragment.setPriceDatas(data.getData());
                }
            }
        });
    }

    /*public void getCityData() {
        DialogHelper.showProgressDialog(activity, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getPickAPI().getAreaSecond(repertory.getAreaCode()).enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                DialogHelper.dismissProgressDialog();
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    activity.setCityDatas(data.getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }*/

    public void getFilterTypeData() {
        APIManager.getInstance().getPickAPI().tenderNewTypeList().enqueue(new ICallBack<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PickSelectEntity>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    newPickBiddingListFragment.setTypeDatas(data.getData());
                }
            }
        });
    }

    public void getFilterStatusData() {
      /*  ArrayList<PickSelectEntity> datas = new ArrayList<>();
        PickSelectEntity pick0 = new PickSelectEntity();
        pick0.setNo("0");
        pick0.setProjectscale("招标中");
        datas.add(pick0);
        PickSelectEntity pick3 = new PickSelectEntity();
        pick3.setNo("3");
        pick3.setProjectscale("招标结束");
        datas.add(pick3);
        activity.setStatusDatas(datas);*/
        Map map = new HashMap();
        map.put("areacode", repertory.getAreaCode());
        APIManager.getInstance().getPickAPI().getProjectStatus(map).enqueue(new ICallBack<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<PickSelectEntity>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    newPickBiddingListFragment.setStatusDatas(data.getData());
                }
            }
        });
    }

    public void getBiddingMapList(String distance, String typeNo, String statusNo, String price, boolean b, String searchName, String goodsType,double latitude,double longitude) {
        map = new HashMap();
        page = b ? page + 1 : 1;

        map.put("distance", distance);
        map.put("limit", 10);
        map.put("name", searchName);
        map.put("page", page);
        map.put("state", statusNo);
        map.put("longitude", longitude);
        map.put("latitude", latitude);
        if ("0".equals(typeNo))
            typeNo = "";
            map.put("type", typeNo);
        if (!"".equals(price) && price != null)
            map.put("price", price);
        if (!TextUtils.isEmpty(goodsType)) {
            map.put("goodsType", goodsType);
        }
        DialogHelper.showProgressDialog2(newPickBiddingListFragment.getActivity(), null, "加载中", 0, true, null,false);
        APIManager.getInstance().getPickAPI().getBiddingMapList(map).enqueue(new ICallBack<BaseEntity<ListResponse<List<BiddingEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<BiddingEntity>>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }
                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    newPickBiddingListFragment.showMapList(data.getData().getList(),b);
                    newPickBiddingListFragment.setbiddingListEntityMapList(data.getData().getList(),b,page);
                } else {
                    MToast.showToast(newPickBiddingListFragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    public void getBiddingList(String cityNo, String typeNo, String statusNo, String price, boolean b, String search, String provinceNo, String goodsType,String sortMethod,String comNo) {
        map = new HashMap();
        page = b ? page + 1 : 1;
        if (!"".equals(provinceNo) && provinceNo != null)
            map.put("province", provinceNo);
        if (!"".equals(cityNo) && cityNo != null)
            map.put("city", cityNo);
//        map.put("companyName", "");
        map.put("limit", 10);
        map.put("keyword", search);
        map.put("current", page);
        map.put("state", statusNo);
        map.put("comNo",comNo);
        if (!"".equals(typeNo) && typeNo != null)
            map.put("type", typeNo);
        if (!"".equals(price) && price != null)
            map.put("price", price);
        if (!TextUtils.isEmpty(goodsType)) {
            map.put("goodsTypeNo", goodsType);
        }
        map.put("sortMethod", Integer.valueOf(sortMethod));
        map.put("queryPosition", "10");
        DialogHelper.showProgressDialog2(newPickBiddingListFragment.getActivity(), null, "加载中", 0, true, null,false);
        APIManager.getInstance().getPickAPI().queryHomeEsPage(map).enqueue(new ICallBack<BaseEntity<ListResponse<List<TenderAllListNewEntity>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListResponse<List<TenderAllListNewEntity>>> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    newPickBiddingListFragment.showList(data.getData().getList(),b);
                } else {
                    MToast.showToast(newPickBiddingListFragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    public void getUrlSetting(String id) {
        DialogHelper.showProgressDialog2(newPickBiddingListFragment.getActivity(), null, "加载中", 0, true, null,false);
        APIManager.getInstance().getPickAPI().getUrlSetting("competitivePurchase").enqueue(new ICallBack<BaseEntity<H5ReEntity>>() {
            @Override
            public void onSuccess(BaseEntity<H5ReEntity> data) {
                if (data == null || data.getState() == null) {
                    return;
                }

                if (data.getState().equals(APIManager.RESPONSE_OK)) {
                    String url = data.getData().getUrl() + "?id=" + id;
                    String lng = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "");
                    String lat = SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "");
                    url = url + "&lng=" + lng + "&lat=" + lat;
                    MLog.d("api", "H5跳转链接  " + url);
                    newPickBiddingListFragment.getUrl(url,id);
                } else {
                    MToast.showToast(newPickBiddingListFragment.getActivity(), data.getMsg());
                }
            }
        });
    }

    public void getProvinceData(int type) {
        DialogHelper.showProgressDialog2(newPickBiddingListFragment.getActivity(), null, "加载中", 0, true, null,false);
        APIManager.getInstance().getPickAPI().getAddressEntityCityList().enqueue(new ICallBack<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> data) {
                if (data != null && data.getData() != null && data.getData().size() > 0) {
                    List<PickSelectEntity> entities = new ArrayList<>();
                    for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> datum : data.getData()) {
                        entities.add(new PickSelectEntity(datum.getNo(), datum.getSimpleName()));
                    }
                    entities.add(0, mAll);
                    newPickBiddingListFragment.setChooseItemData(type, entities);
                    newPickBiddingListFragment.setProvinceDatas(data.getData());
                }
            }
        });
    }

    public void getAddressCityData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData, String no, int type) {
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> scrDatum : scrData) {
            if (scrDatum.getId().equals(no)) {
                List<AddressEntity<List<AddressEntity>>> children = scrDatum.getChildren();
                if (children != null && children.size() > 0) {
                    List<PickSelectEntity> entities = new ArrayList<>();
                    for (AddressEntity<List<AddressEntity>> child : children) {
                        entities.add(new PickSelectEntity(child.getNo(), child.getSimpleName()));
                    }
                    entities.add(0, mAll);
                    newPickBiddingListFragment.setChooseItemData(type, entities);
                }
            }
        }
    }

    public void getAddressCityDataDialog(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData, String no) {
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> scrDatum : scrData) {
            if (scrDatum.getId().equals(no)) {
                List<AddressEntity<List<AddressEntity>>> children = scrDatum.getChildren();
                if (children != null && children.size() > 0) {
                    List<PickSelectEntity> entities = new ArrayList<>();
                    for (AddressEntity<List<AddressEntity>> child : children) {
                        entities.add(new PickSelectEntity(child.getNo(), child.getSimpleName()));
                    }
                    entities.add(0, mAll);
                    newPickBiddingListFragment.setCityDatas(entities);
                }
            }
        }
    }

    //新增类型过滤接口
    public void getTenderGoodsCategoryAllList(String category) {
        DialogHelper.showProgressDialog2(newPickBiddingListFragment.getContext(), null, "数据加载中...", 0, false, null,false);
        Map map = new HashMap();
        map.put("type", category);
        APIManager.getInstance().getPickAPI().getTenderGoodsCategoryAllList(map).enqueue(new Callback<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>> call, Response<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    newPickBiddingListFragment.setTenderGoodsCategoryAllList(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>>>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }


    public void getBidSortSelect() {
        APIManager.getInstance().getPickAPI().getAllSortSelect("9").enqueue(new Callback<BaseEntity<List<PickSelectEntity>>>() {
            @Override
            public void onResponse(Call<BaseEntity<List<PickSelectEntity>>> call, Response<BaseEntity<List<PickSelectEntity>>> response) {
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }

                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    newPickBiddingListFragment.setSortDatas(response.body().getData());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<List<PickSelectEntity>>> call, Throwable t) {

            }
        });
    }

    public String getAreaCode() {
        return repertory.getAreaCode();
    }

    public void findCustomerServiceImAccount(String customerServiceContactsId) {
        DialogHelper.showProgressDialog(newPickBiddingListFragment.getActivity(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("customerServiceContactsId", customerServiceContactsId);
        APIManager.getInstance().getPickAPI().getfindCustomerServiceImAccount(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_FAIL)) {
                    newPickBiddingListFragment.checkAllowDialog(response.body().getMsg());
                } else {
                    String dataIMid = response.body().getData().toString();
                    IMUtils.getInstance().buildSingleTalking(dataIMid);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });

    }

    public void checkAllowBidQuestion(String bidNo,String bidType) {
        DialogHelper.showProgressDialog(newPickBiddingListFragment.getActivity(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("bidNo", bidNo);
        APIManager.getInstance().getPickAPI().checkAllowBidQuestion(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_FAIL)) {
                    newPickBiddingListFragment.checkAllowDialog(response.body().getMsg());

                } else {
                    if(!TextUtils.isEmpty(bidType)){
                        PickInquireByLetterActivity.start(newPickBiddingListFragment.getActivity(), bidNo, "jj",Integer.parseInt(bidType));
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void editBid(String bidNo, int position) {
        DialogHelper.showProgressDialog(newPickBiddingListFragment.getActivity(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("bidNo", bidNo);
        APIManager.getInstance().getPickAPI().editBid(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null || response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    newPickBiddingListFragment.setTvIsGz(position);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void countByBusiness(String businessNo) {
        DialogHelper.showProgressDialog(newPickBiddingListFragment.getActivity(), null, "获取信息中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map map = new HashMap();
        map.put("businessNo", businessNo);
        map.put("businessType", 2);
        APIManager.getInstance().getPickAPI().countByBusiness(map).enqueue(new Callback<BaseEntity>() {
            @Override
            public void onResponse(Call<BaseEntity> call, Response<BaseEntity> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    if (!"可进行举报监督操作".equals(response.body().getData())) {
                        newPickBiddingListFragment.checkAllowDialog(response.body().getData().toString());
                    }else{
                        ReportActivity.start(newPickBiddingListFragment.getActivity(), businessNo, "2");
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity) {
        DialogHelper.showProgressDialog(newPickBiddingListFragment.getContext(), null, "登录中", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new Callback<BaseEntity<LoginEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<LoginEntity>> call, Response<BaseEntity<LoginEntity>> response) {

                DialogHelper.dismissProgressDialog();
                if (response.body().getState() == null) {
                    return;
                }
                if (response.body().getState().equals(APIManager.RESPONSE_OK)) {
                    OneKeyLoginManager.getInstance().finishAuthActivity();
                    if (response.body().getData().isNeedRegister()) {
                        Intent intent = new Intent(newPickBiddingListFragment.getContext(), SetPwdActivity.class);
                        intent.putExtra("mobile", response.body().getData().getPhone());
                        newPickBiddingListFragment.startActivity(intent);
                    } else {
                        //登录成功逻辑
                        loginImModel(response);

                        /*saveUserInfo(response.body().getData());
                        activity.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                        JPushInterface.setAlias(activity, 1, response.body().getData().getPhone());
                        getUserInfo();*/
                    }
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    //网易IM登陆
    private void loginImModel(Response<BaseEntity<LoginEntity>> response) {
//        NimUIKit.login(new LoginInfo(response.body().getData().getImAccount(), response.body().getData().getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
                DialogHelper.dismissProgressDialog();
                SharedPreferenceUtil.getInstance().cleatData();
                saveUserInfo(response.body().getData());
                MToast.showToast(newPickBiddingListFragment.getContext(), "登录成功");
                newPickBiddingListFragment.loginSucceed(response.body().getData(), response.body().getData().getPhone());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, response.body().getData().getToken());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, response.body().getData().getPhone());
                JPushInterface.setAlias(newPickBiddingListFragment.getContext(), 1, response.body().getData().getPhone());
                getUserInfo();
//            }
//
//            @Override
//            public void onFailed(int code) {
//                DialogHelper.dismissProgressDialog();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                DialogHelper.dismissProgressDialog();
//            }
//        });
    }

    public void getUserInfo() {
        DialogHelper.showProgressDialog(newPickBiddingListFragment.getContext(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new Callback<BaseEntity<UserMsgEntity>>() {
            @Override
            public void onResponse(Call<BaseEntity<UserMsgEntity>> call, Response<BaseEntity<UserMsgEntity>> response) {
                DialogHelper.dismissProgressDialog();
                if (response.body() == null) return;
                if (response.body().getData() == null) return;
                if (response.body().getState().equals("ok")) {
                    newPickBiddingListFragment.getUserMsgSucceed(response.body().getData());
                } else {
                    MToast.showToast(newPickBiddingListFragment.getContext(), response.body().getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
                DialogHelper.dismissProgressDialog();
            }
        });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
        repertory.saveAccount(loginEntity.getPhone());

//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
//        Preferences.saveUserAccount(loginEntity.getImAccount());
//        Preferences.saveUserToken(loginEntity.getImToken());
    }

}
